package com.tledu.stu_manager.controller.role; /**
 *
 */

import com.alibaba.fastjson.JSONObject;
import com.tledu.stu_manager.constant.Constant;
import com.tledu.stu_manager.dao.RoleDao;
import com.tledu.stu_manager.exception.CustomException;
import com.tledu.stu_manager.model.Role;
import com.tledu.stu_manager.result.Result;
import com.tledu.stu_manager.service.RoleService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "RoleAddServlet", value = "/role/add")
public class RoleAddServlet extends HttpServlet {
    private RoleService roleService;

    @Override
    public void init() throws ServletException {
        super.init();
        roleService = new RoleService(new RoleDao());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/role/role-add.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType(Constant.CONTENT_TYPE);
        PrintWriter out = response.getWriter();

        Role role = new Role();
        role.setRoleName(request.getParameter("roleName"));

        try {
            roleService.addRole(role);
            out.print(JSONObject.toJSONString(new Result(200, true, "添加成功")));
        } catch (CustomException e) {
            e.printStackTrace();
            out.print(JSONObject.toJSONString(new Result(500, false, e.getMessage())));
        }

    }
}
